import os.path
import sys

sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

import click

from dp_analysis.analysis.base import DrawBase
from dp_analysis.db.connection import Mysql
from dp_analysis.utils.data_search import search_region, search_cuisine
from dp_analysis.utils.decorate import decorate


class DrawWordCloudV1(DrawBase):
    """
    绘制用户评论高频词词云(不区分店铺，随机选取部分数据)
    """
    def __init__(self):
        super().__init__()

        self.sql_query = "SELECT " \
                         "b.`comment` " \
                         "FROM shop_info AS a,  shop_comment AS b " \
                         "WHERE a.region={!r} AND a.shop_id=b.shop_id "
        # 临界值，过滤数量小于 50 的词汇
        self.critical_value = 50

    @decorate(obj_name="DrawWordCloud")
    def analyse(self, db, region, cuisine, limit):
        with Mysql("dp", db) as mysql:
            connection = mysql.engine.connect()

            # 读取停用词
            self.read_stopwords()

            region_list = list()
            if region == "all":
                # 绘制所有地区的词云
                for (reg, ) in connection.execute("SELECT region FROM regional_table_of_delicacies;").fetchall():
                    region_list.append(reg)
            else:
                region_list = [region]

            for region in region_list:
                print(f"正在处理{region}地区...")
                text_dict = dict()

                save_file_name = f"{region}地区-"
                save_file_path = f"word_cloud/word_cloud_v1/{region}/"
                if cuisine == "all":
                    save_file_name += "所有菜系-"
                    save_file_path += f"所有菜系/"
                else:
                    save_file_name += f"{cuisine}-"
                    save_file_path += f"{cuisine}/"
                save_file_name += "评论高频词云"

                # 生成用于查询的url
                sql = self.sql_query.format(region)
                # 获取用户输入的菜系，如果为 all， 则表示所有
                if cuisine != "all":
                    sql += f"AND a.category={cuisine!r} "
                # 获取使用的评论数量
                sql += f"limit {limit};"

                # 评论词汇统计
                number = 0
                for (comment, ) in connection.execute(sql).fetchall():
                    for word in self.participle(comment):
                        if word in self.stopwords_set:
                            continue
                        text_dict.setdefault(word, 0)
                        text_dict[word] += 1
                    number += 1
                    if number % 1000 == 0:
                        print(f"已处理{number}条评论...")
                print(f"共处理评论{number}条！")
                if not number:
                    print(f"本地区无评论信息！\n\n")
                    continue

                text_list = list()
                for _str, _count in text_dict.items():
                    # 低频词过滤
                    if _count < self.critical_value:
                        continue
                    # _count // critical_value，对高频词进行降维
                    text_list.extend([_str] * (_count // self.critical_value))

                # 绘制词云
                self.draw_word_cloud_v2(region, save_file_name, text_list, save_file_name, save_file_path)

    __call__ = analyse


@click.command()
@click.option("--db", default=0, help="请选择使用的数据库")
@click.option("--region", default="all", help="12大地区通过helpers.py获取")
@click.option("--cuisine", default="all", help="所有菜系通过helpers.py获取")
@click.option("--limit", default=10000, help="请选择使用的评论数量")
def main(db, region, cuisine, limit):
    if region != "all" and region not in search_region(db):
        raise Exception(f"输入地区{region}不在可选范围内...")

    if cuisine != "all" and cuisine not in search_cuisine(db, region):
        raise Exception(f"{region}地区不包含{cuisine}热门菜系...")

    draw = DrawWordCloudV1()
    draw.analyse(int(db), region, cuisine, limit)


if __name__ == '__main__':
    main()
